//index.js

var CosCloud = require('../../lib/cos-wx-sdk-v4');
//var CosCloud = require('../../lib/cos-js-sdk-v4');
var CryptoJS = require('../../lib/crypto');
var config = require('./config');
var guid = require('../../lib/util');
var Promise = require('../../lib/es6-promise.min');
//var request = require('../../lib/request.js');
var appid = config.appid;
var bucket = config.bucket;
var region = config.region;
var sid = config.sid;
var skey = config.skey;



var getSignature = function (once) {
    var that = this;
    var random = parseInt(Math.random() * Math.pow(2, 32));
    var now = parseInt(new Date().getTime() / 1000);
    var e = now + 60; //签名过期时间为当前+60s
    var path = ''; //多次签名这里填空
    var str = 'a=' + appid + '&k=' + sid + '&e=' + e + '&t=' + now + '&r=' + random +
        '&f=' + path + '&b=' + bucket;
    var sha1Res = CryptoJS.HmacSHA1(str, skey);//这里使用CryptoJS计算sha1值，你也可以用其他开源库或自己实现
    var strWordArray = CryptoJS.enc.Utf8.parse(str);
    var resWordArray = sha1Res.concat(strWordArray);
    var res = resWordArray.toString(CryptoJS.enc.Base64);
    return res;
};

var cos = new CosCloud({
    appid: appid, // APPID 必填参数
    bucket: bucket, // bucketName 必填参数
    region: region, // 地域信息 必填参数 华南地区填gz 华东填sh 华北填tj
    getAppSign: function (callback) {//获取签名 必填参数

        // 下面简单讲一下获取签名的几种办法
        // 首先，签名的算法具体查看文档：[COS V4 API 签名算法](https://www.qcloud.com/document/product/436/6054)

        // 1.搭建一个鉴权服务器，自己构造请求参数获取签名，推荐实际线上业务使用，优点是安全性好，不会暴露自己的私钥
        // 拿到签名之后记得调用callback
        /*
        wx.request({
            url: 'SIGN_URL',
            data: {once: false},
            dataType: 'text',
            success: function (result) {
                var sig = result.data;
                callback(sig);
            }
        });
         */

        // 2.直接在浏览器前端计算签名，需要获取自己的 accessKey 和 secretKey, 一般在调试阶段使用
        // 拿到签名之后记得调用 callback
        var res = getSignature(false); // 这个函数自己根据签名算法实现
        callback(res);

        // 3.直接复用别人算好的签名字符串, 一般在调试阶段使用
        // 拿到签名之后记得调用 callback
        // callback('YOUR_SIGN_STR')

    },
    getAppSignOnce: function (callback) { //单次签名，必填参数，参考上面的注释即可
        // 填上获取单次签名的逻辑
        var res = getSignature(true); // 这个函数自己根据签名算法实现
        callback(res);
    }
});
var ERR = {
    // 其他错误码查看文档：https://www.qcloud.com/document/product/436/6059
    'ERROR_CMD_COS_PATH_CONFLICT': '文件/目录已存在',
    'ERROR_CMD_FILE_NOTEXIST': '文件/目录不存在',
    'ERROR_SAME_FILE_UPLOAD': '不能覆盖已存在文件'
};

var app = getApp()

//获取应用实例
Page({
    data: {
        userInfo: {},
        windowWidth: '',
        openId: '',
        index: 0,
        imageList: [],
        src: [],
        percent: 0,
        total: 0,
        max: 12,
        loading: false,
        text: '上传照片',
        fileNameList: []
    },
    onLoad: function () {
        console.log('onLoad')
        var that = this
        //调用应用实例的方法获取全局数据
        app.getUserInfo(function (userInfo) {
            //更新数据
            that.setData({
                userInfo: userInfo,
                total: 0
            })
        }),
            wx.getSystemInfo({
                success: function (res) {
                    that.setData({
                        windowWidth: res.windowWidth
                    })
                }
            })
        console.log(that.data.windowWidth)
    },
    //下拉刷新，取消所有选择图片

    onPullDownRefresh: function () {
        var that = this;
        console.log('pullDownRefresh')
        var length = that.data.imageList.length
        if (length > 0) {
            wx.showModal({
                title: '确认框',
                content: '是否取消所有所选照片？',
                success: function (res) {
                    if (res.confirm) {
                        setTimeout(function () {
                            that.setData({
                                imageList: [],
                                total: 0,
                            })
                        }, 1000)
                    }
                }
            })
            wx.stopPullDownRefresh()
        }
    },
    //分享小程序
    onShareAppMessage: function () {
        return {
            title: '小鱼快印',
            desc: '打印第一品牌',
            path: '/pages/index/index'
        }
    },

    // 回调统一处理函数
    createCallBack: function (msg) {
        var that = this;
        return function (result) {
            console.log(result);
            that.loading(0);
            if (result.errMsg != 'request:ok' && result.errMsg != 'uploadFile:ok') {
                wx.showModal({
                    title: '请求出错', content: '请求出错：' + result.errMsg + '；状态码：' + result.statusCode,
                    showCancel: false
                });
            } else if (result.data.code) {
                wx.showModal({
                    title: '返回错误',
                    content: (msg || '请求') + '失败：' + (ERR[result.data.message] || result.data.message) +
                    '；状态码：' + result.statusCode, showCancel: false
                });
            } else {
                wx.showToast({ title: (msg || '请求') + '成功', icon: 'success', duration: 3000 });
            }
        }
    },
    // 回调统一处理函数
    loading: function (isLoading, msg) {
        if (isLoading) {
            wx.showToast({ title: (msg || '正在请求...'), icon: 'loading', duration: 60000 });
        } else {
            wx.hideToast();
        }
    },
    // 创建目录
    createFolder: function () {
        cos.createFolder(this.createCallBack('1. /test 目录创建'), this.createCallBack(), bucket, '/test', 'folder_first_attr'); // 最后的 bizAttr 参数可省略
    },
    // 列出目录
    getFolderList: function () {
        cos.getFolderList(this.createCallBack('2. /test 目录列出'), this.createCallBack(), bucket, '/test');
    },
    // 查询目录属性
    getFolderStat: function () {
        cos.getFolderStat(this.createCallBack('3. /test 目录属性查询'), this.createCallBack(), bucket, '/test');
    },
    // 更新目录属性
    updateFolder: function () {
        cos.updateFolder(this.createCallBack('4. /test 目录属性更新'), this.createCallBack(), bucket, '/test', 'folder_new_attr');
    },
    // 删除目录
    deleteFolder: function () {
        cos.deleteFolder(this.createCallBack('5. /test 目录删除'), this.createCallBack(), bucket, '/test');
    },
    successPromise: function (tempFilePath, i, len, fileName) {
        var that = this;
        return function (result) {
            that.data.imageList.push(tempFilePath)
            that.data.fileNameList.push(fileName)
            console.log(result);
            if (result.statusCode === 200) {
                console.log('upload cos files is done.');
                that.setData({
                    imageList: that.data.imageList,
                    total: that.data.imageList.length
                })
                if (i === len) {
                    that.setData({
                        loading: false
                    })
                }
            }

        }

    },
    errorPromise: function (i, len) {
        return function (result) {

            console.log(result);
            if (result.statusCode != 200) {
                console.log('upload cos files is failed.');
            }
            if (i === len) {
                that.setData({
                    loading: false
                })
            }

        }

    },

    //选择文件
    chooseImageListener: function () {
        var that = this;
        var chooseNumber = that.data.total;
        var chooseMax = that.data.max;
        var chooseUpper = chooseMax - 9;
        var fileName = null;
        //if (chooseUpper < chooseNumber < chooseMax)   注意：不存在这种判别方式
        if (chooseNumber > chooseUpper && chooseNumber < chooseMax) {
            console.log('chooseNumber > chooseUpper && chooseNumber < chooseMax')
            wx.chooseImage({
                count: chooseMax - chooseNumber,
                sourceType: ['album', 'camera'],
                sizeType: ['original', 'compressed'],
                success: function (res) {
                    that.setData({
                        loading: true
                    })
                    console.log(res)
                    var len = res.tempFilePaths.length;
                    for (var i in res.tempFilePaths) {
                        var tempFilePath = res.tempFilePaths[i]
                        fileName = guid();
                        cos.uploadFile(that.successPromise(tempFilePath, i + 1, len, fileName), that.errorPromise(i + 1, len), bucket, fileName, tempFilePath, 0);

                    }
                }
            })
        } else if (chooseNumber < chooseUpper || chooseNumber === chooseUpper) {
            console.log('chooseNumber < chooseUpper')
            wx.chooseImage({
                count: 9,
                sourceType: ['album', 'camera'],
                sizeType: ['original', 'compressed'],
                success: function (res) {
                    that.setData({
                        loading: true
                    })
                    console.log(res)
                    var len = res.tempFilePaths.length;
                    for (var i = 0; i < len; i++) {
                        var tempFilePath = res.tempFilePaths[i]
                        fileName = guid() + '.jpg';
                        cos.uploadFile(that.successPromise(tempFilePath, i + 1, len, fileName), that.errorPromise(i + 1, len), bucket, fileName, tempFilePath, 0);
                    }
                }
            })
        } else {
            console.log('chooseNumber = ' + chooseNumber)
            console.log('chooseUpper = ' + chooseUpper)

            wx.showToast({
                title: "已达数量上限",
                duration: 2000
            })

        }


    },

    //删除图片
    cancelImageListener: function (e) {
        var that = this;
        var current = e.target.id
        wx.showModal({
            title: '确认框',
            content: '是否取消上传该图片？',
            success: function (res) {
                if (res.confirm) {

                    var tempFileNameList = '/' + that.data.fileNameList.splice(current, 1)
                    if (that.data.imageList.length === 1) {
                        that.setData({
                            imageList: [],
                            total: 0,
                            fileNameList: []
                        })
                    } else {
                        var tempImageList = that.data.imageList.splice(current, 1)
                        that.setData({
                            imageList: that.data.imageList,
                            total: that.data.imageList.length,
                            fileNameList: that.data.fileNameList
                        })
                    }
                    cos.deleteFile(that.createCallBack('delete file success'), that.createCallBack(), bucket, tempFileNameList);
                    //cos.getFileStat(that.createCallBack('find'), that.createCallBack(), bucket, tempFileNameList);
                    console.log('用户点击确定, 取消上传 : ' + current)
                }
            }
        })

    },
    //预览图片
    previewImageListener: function (e) {
        var current = e.target.dataset.src

        wx.previewImage({
            current: current,
            urls: this.data.imageList
        })
    },
    //
    createOrderListener: function () {
        var that = this;
        //this.showLoading('正在删除图片…');
        console.log(that.data.userInfo.nickName)
        console.log(that.data.imageList)
        //var list = JSON.stringify(that.data.fileNameList);
        var list = that.data.fileNameList;
        console.log(list);
        wx.request({
            method: 'GET',
            //url: api.getUrl('/delete'),
            //dataType: 'json',
            url: 'https://www.xyky.me/applet/album/order',
            data: {
                'nickName': that.data.userInfo.nickName,
                'fileNameList': list
            },
            header: {
                //'content-type': 'application/json'
                 'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
                console.log(res.data)
                var orderid = res.data.orderid
                if(res.data.msg === "success"){
                    wx.redirectTo({
                        url:'../order/order?orderid=' + orderid
                    })
                }
            }
        })
    },
    // 查询文件属性
    getFileStat: function () {
        cos.getFileStat(this.createCallBack('7. /test.png 文件属性查询'), this.createCallBack(), bucket, '/test.png');
    },
    // 更新文件属性
    updateFile: function () {
        cos.updateFile(this.createCallBack('8. /test.png 文件属性更新'), this.createCallBack(), bucket, '/test.png', 'file_new_attr');
    },
    // 删除文件
    deleteFile: function () {
        cos.deleteFile(this.createCallBack('9. /test.png 文件删除'), this.createCallBack(), bucket, '/test.png');
    },
    // 复制文件
    copyFile: function () {
        cos.copyFile(this.createCallBack('10. /test.png 文件复制'), this.createCallBack(), bucket, '/test.png', '/test-cp.png', 0); // overWrite==0 表示不允许覆盖文件 1表示允许覆盖
    },
    // 移动文件
    moveFile: function () {
        cos.moveFile(this.createCallBack('11. /test.png 文件移动'), this.createCallBack(), bucket, '/test.png', '/test-mv.png', 0); // overWrite==0 表示不允许覆盖文件 1表示允许覆盖
    }


});
